# -*-* encoding:UTF-8 -*-
# author            : mengy
# date              : 2019/1/29
# python-version    : Python 3.7.0
# description       : 文章service

import json
from com.articles.microapp.utils.constants import CommonConstants as consts
from com.articles.microapp.utils import db_utils
from com.articles.microapp.dao.articles_dao import ArticleDao


class ArticleService(object):
    __DbUtil = db_utils.DbUtils()
    __ArticleDao = ArticleDao()

    def query_banner(self, page=[consts.DEFAULT_PAGE_NO, consts.DEFAULT_PAGE_SIZE]):
        return self.__ArticleDao.get_banner(page=page)

    def query_articles(self, params={}, page=[consts.DEFAULT_PAGE_NO, consts.DEFAULT_PAGE_SIZE]):
        return self.__ArticleDao.get_articles(params, page)

    def query_article(self, article_id):
        article = self.__ArticleDao.get_article(article_id)
        # 获取同类型的文章，作为上下篇
        articles = self.__ArticleDao.get_articles(params={'articleType': str(article.articleType)})
        i = 0
        for art in articles['list']:
            if i < len(articles):
                if article.articleId == art['articleId']:
                    i += 1
                    continue
                if not article.nextArt or not article.previousArt:
                    if not article.previousArt:
                        article.previousArt = {
                            "articleId": art['articleId'],
                            "title": art['title']
                        }
                        i += 1
                        continue
                    else:
                        article.nextArt = {
                            "articleId": art['articleId'],
                            "title": art['title']
                        }
                        i += 1
                        continue
                else:
                    break
            else:
                break
        return article


if __name__ == '__main__':
    article = ArticleService()
    articles = article.query_articles()
    # for a in articles:
    #     print(json.dumps(a.__dict__, ensure_ascii=False))
    #     print(a.articleTags)
    #     print(a.articleType)
    # article = article.query_article('b0eb662e-2532-11e9-ab14-d663bd873d93')
    # print(article)
    # print(article.articleTags)
    # print(json.dumps(article.__dict__, ensure_ascii=False))
    # print(article.query_banner())
